package day07;

import java.io.*;
import java.net.Socket;
import java.util.Objects;
import java.util.Scanner;

/**
 * @author zouran
 * createDate：2024/6/28  16:53
 */
public class ClientPlus {
    public static void main(String[] args) throws IOException {
        String host = "127.0.0.1";
        int port = 10000;
        Socket socket = new Socket(host, port);
        System.out.println("Client Start！");
        onSend(socket);
        onReceive(socket);
    }

    public static void onSend(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        new Thread(() -> {
            while (true) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("Please input message (exit represent end):");
                String message = scanner.nextLine();
                if (Objects.equals(message, "exit")) {
                    System.exit(0);
                    break;
                }
                try {
                    bufferedWriter.write(message);
                    bufferedWriter.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("Send Success!");
            }
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }

    public static void onReceive(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        new Thread(() -> {
            while (true) {
                char[] chars = new char[1024];//发送的最大消息不超过1024个字符
                int len;
                try {
                    len = bufferedReader.read(chars);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                System.out.print("Receive server message: ");
                System.out.println(new String(chars, 0, len));
                System.out.println("Please input message (exit represent end):");
            }
        }).start();
    }
}
